package com.orangelife.mobile.parkingcard.activity;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.curry.android.http.HttpUtil;
import com.curry.android.http.OrangeDataHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.google.gson.reflect.TypeToken;
import com.markupartist.android.widget.PullToRefreshListView;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.common.biz.PullListViewImpl;
import com.orangelife.mobile.common.biz.PullListViewRefreshOrLoad;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.constants.ParkingCardURL;
import com.orangelife.mobile.parkingcard.adapter.PayRecordAdapter;
import com.orangelife.mobile.util.JsonReponseHandler;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ParkingCardFeeMineActivity extends OrangeLifeBaseActivity {
    /**
     * 标题
     */
    private TextView tvTitle;
    /**
     * 累计缴费
     */
    private TextView tvTotalRecharge;
    /**
     * 上次缴费时间
     */
    private TextView tvLastTimeRechargeTime;
    /**
     * 无停车卡时显示广告
     */
    private RelativeLayout rlParkingCarApply;
    /**
     * 有停车卡时显示列表
     */
    private RelativeLayout rlPayRecord;
    /**
     * 缴费记录
     */
    private PullToRefreshListView lvPayRecord;
    /**
     * 初始化页数
     */
    private int pageNo = Constant.PAGE_NO_DEFAULT;
    /**
     * 初始化页面的数据数量
     */
    private int pageSize = Constant.PAGE_SIZE_DEFAULLT;
    /**
     * 缴费适配器
     */
    private PayRecordAdapter<Map<String, Object>> adapter;
    private static final int PAY_RECORD = 0;
    private List<Map<String, Object>> recordList, recordList2;
    private Handler mHandler;
    private PullListViewRefreshOrLoad pullListView;
    private String cardsID;
    private Button btnApplyParkingCard;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parking_card_fee_mine);
        initView();
        setRequestCard();
        setAdapter();
        getMyPayRecordFromServer();
        pullListView();

    }

    /**
     * 判断是否有停车卡
     */
//	private void setRequestCard(){
//		//		String url = Constant.URL_PARKCARD_ISCARD;
//		//		JSONRequest.getInstance().sendRequest(JSONRequest.GET, url, null, handler, CARD, HttpUtil.ACTION_URI);
//		Map<String, Object> map = new HashMap<String, Object>();
//		Map<String, Object> rootMap = new HashMap<String, Object>();
//		rootMap.put("map", map);
////		rootMap.put("url", ParkingCardURL.PARKCARD_LIST);
//		rootMap.put("url", ParkingCardURL.PARKCARD_LIST);
//		rootMap.put("wat", 1);
//		new JSONRequest(JSONRequest.GET, rootMap, handler, HttpUtil.ACTION_URI);
//	}
    private void setRequestCard() {
        HashMap<String, String> map = new HashMap<String, String>();
        VolleyHttpUtil.getInstance().getWithCallback(ParkingCardURL.PARKCARD_LIST, map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                @SuppressWarnings("unchecked")
                Map<String, Object> mapDetail = (Map<String, Object>) OrangeDataHandler.getMapWithEntityNoGson(
                        jsonObject);
                if (mapDetail.size() > 0) {
                    if (mapDetail.get("count").equals("0")) {/**没停车卡*/
                        rlParkingCarApply.setVisibility(View.VISIBLE);
                    } else {/**有停车卡*/
                        rlPayRecord.setVisibility(View.VISIBLE);
                    }
                } else {/**没有停车卡*/
                    rlParkingCarApply.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    //	private void getMyPayRecordFromServer() {
//		showDialog(this);
////		String url = Constant.URL_PARKCARD_PAY_MINE;
//		String url = ParkingCardURL.PARKCARD_PAY_MINE;
//		Map<String,Object> map = new HashMap<String, Object>();
//		map.put("pageIndex",pageNo);
//		map.put("pageSize", pageSize);
////		map.put("cardsID", cardsID);
////		map.put("cardsID", "05F54694-25CB-2DE5-0207-14FA1E374467");
//		JSONRequest.getInstance().sendRequest(JSONRequest.GET, url, map, handler, PAY_RECORD, HttpUtil.ACTION_URI);
//	}
    private void getMyPayRecordFromServer() {
        showDialog(this);
//		String url = Constant.URL_PARKCARD_PAY_MINE;
        String url = ParkingCardURL.PARKCARD_PAY_MINE;
        HashMap<String,String> map = new HashMap<String, String>();
        map.put("pageIndex",String.valueOf(pageNo));
        map.put("pageSize", String.valueOf(pageSize));

        VolleyHttpUtil.getInstance().getWithCallback(url,map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                recordList2 = OrangeDataHandler.getListFromJsonWithPageEntity(
                        jsonObject, new TypeToken<List<Map<String, Object>>>() {
                        }.getType(), adapter, dialog);
                updateListView(recordList2);
                if(recordList2.size()>0){
                    setText(recordList2.get(0).get("total").toString(), recordList2.get(0).get("latest_time").toString());
                }
            }
        });
    }

    private void pullListView() {
        pullListView = new PullListViewImpl() {
            @Override
            public void refresh() {
                recordList.clear();
                pageNo = 1;
                notifyPage();
            }

            @Override
            public void loadMore() {
                pageNo += 1;
                notifyPage();
            }
        };
        pullListView.pullListView(lvPayRecord, mHandler);
    }

    /**
     * 更新界面
     */
    @SuppressWarnings("unchecked")
    private void setList() {
//		String value = "{\"people\":[{\"tscreate\":\"Brett\",\"goodsCost\":\"McLaughlin\",\"remark\":\"aaaa\"}]}";
//		recordList = (List<Map<String, Object>>) JSONHelper.jsonToMap(
//				value).get("people");
        adapter.setList(recordList);
        adapter.notifyDataSetChanged();
    }

    private void setAdapter() {
        recordList = new ArrayList<Map<String, Object>>();
        adapter = new PayRecordAdapter<Map<String, Object>>(this, recordList);
        lvPayRecord.setPullLoadEnable(false);
        lvPayRecord.setAdapter(adapter);
    }

    private void initView() {
        btnApplyParkingCard = (Button) findViewById(R.id.btnApplyParkingCard);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        tvTotalRecharge = (TextView) findViewById(R.id.tvTotalRecharge);
        tvLastTimeRechargeTime = (TextView) findViewById(R.id.tvLastTimeRechargeTime);
        rlParkingCarApply = (RelativeLayout) findViewById(R.id.rlParkingCarApply);
        rlPayRecord = (RelativeLayout) findViewById(R.id.rlPayRecord);
        lvPayRecord = (PullToRefreshListView) findViewById(R.id.lvPayRecord);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(R.string.park_pay_mine);
        mHandler = new Handler();
        btnApplyParkingCard.setOnClickListener(listener);
    }

    /**
     * 请求数据与更新界面
     */
    private void notifyPage() {
        getMyPayRecordFromServer();
        pullListView.onLoad(lvPayRecord);
        if (recordList != null) {
            adapter.setList(recordList);
            adapter.notifyDataSetChanged();
        }
    }

    Handler handler = new Handler() {
        @SuppressWarnings("unchecked")
        public void handleMessage(android.os.Message msg) {
            DialogHelper.closeDialog(dialog);
            switch (msg.what) {
                case PAY_RECORD:
                    recordList2 = JsonReponseHandler.getListFromJson(
                            String.valueOf(msg.obj), adapter, dialog);
                    updateListView(recordList2);
                    if (recordList2.size() > 0) {
                        setText(recordList2.get(0).get("total").toString(), recordList2.get(0).get("latest_time").toString());
                    }
                    break;
                case 1:
                    @SuppressWarnings("unchecked")
                    Map<String, Object> mapDetail = (Map<String, Object>) JSONHelper.jsonToMap(
                            msg.obj.toString());
                    if (mapDetail.size() > 0) {
                        if (mapDetail.get("count").equals("0")) {/**没停车卡*/
                            rlParkingCarApply.setVisibility(View.VISIBLE);
                        } else {/**有停车卡*/
                            rlPayRecord.setVisibility(View.VISIBLE);
                        }
                    } else {/**没有停车卡*/
                        rlParkingCarApply.setVisibility(View.VISIBLE);
                    }
                    break;
                case 500:
                    ToastHelper.getInstance()._toast(
                            msg.obj.toString());
                    break;
                default:
                    break;
            }
        }

        ;
    };

    /**
     * 设置累计缴费总额和上次缴费时间
     */
    private void setText(String countCost, String time) {
        if (StringUtil.isBlank(countCost)) {
            tvTotalRecharge.setText(Constant.RMB_FLAG+ "0.00");
        } else {
            tvTotalRecharge.setText(Constant.RMB_FLAG + countCost);
        }
        if (StringUtil.isBlank(time)) {
            tvLastTimeRechargeTime.setText("暂无");
        } else {
            tvLastTimeRechargeTime.setText(time);
        }
    }

    /**
     * 刷新下拉列表
     *
     * @param list2
     */
    private void updateListView(List<Map<String, Object>> list2) {
        /** 判断list2是否为空 */
        if (list2 != null && recordList != null) {
            if (list2.size() == 0) {
                lvPayRecord.setPullLoadEnable(false);
                setList();
            } else {
                lvPayRecord.setPullLoadEnable(true);
                recordList.addAll(list2);
                setList();
            }
        } else {
            lvPayRecord.setPullLoadEnable(false);
        }
    }

    public View.OnClickListener listener = new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            switch (view.getId()) {
                case R.id.btnApplyParkingCard:

                    IntentHelper.getInstances().getIntent(ParkingCardFeeMineActivity.this, ApplyForParkingCardBeginActivity.class);

                    finish();


                    break;

                default:
                    break;
            }
        }
    };
}
